export default class GotService {
    constructor() {
        this._apiBase = "https://www.anapioficeandfire.com/api";
    }


    getResource = async (url) => {
        const res = await fetch(`${this._apiBase}${url}`);

        if (!res.ok) {
            throw new Error(`Could not fetch ${url}, status: ${res.status}`);
        }
        return await res.json();
    }

    getAllCharacters = async () => {
        const res = await this.getResource(`/characters?page=5&pageSize=10`);
        return res.map(this._transformCharacter)
    }

    getCharacter = async (id) => {
        const character = await this.getResource(`/characters/${id}`)
        return this._transformCharacter(character);
    }

    getAllHouses = async () => {
        const res = await this.getResource("/houses/")
        return res.map(this._transformHouse)
    }

    getHouse = async (id) => {
        const house = await this.getResource(`/houses/${id}`)
        return this._transformHouse(house)
    }



    getAllBooks = async () => {
        const res = await this.getResource("/books/")
        return res.map(this._transformBook)
    }

    getBook = async (id) => {
        const book = await this.getResource(`/books/${id}/`)
        return this._transformBook(book)
    }



    isSet(data) {
        if (data) {
            return data
        } else {
            return 'no data ;('
        }

    }

    _extractId = (item) => {
        const idRegExp = /\/([0-9]*)$/;
        return item.url.match(idRegExp)[1];
    }

    //функции трансформаторы нужны для того чтобы привести данный в подходящий для нас вид в случае если данные Api могут быть оформлены по разному
    _transformCharacter = (char) => {
        return {
            id: this._extractId(char),
            name: this.isSet(char.name),
            gender: this.isSet(char.gender),
            born: this.isSet(char.born),
            died: this.isSet(char.died),
            culture: this.isSet(char.culture),
        }
    }

    _transformHouse = (house) => {
        return {
            name: house.name,
            region: house.region,
            title: house.title,
            overlord: house.overlord,
            ancestralWeapons: house.ancestralWeapons,
            coatOfArms: house.coatOfArms,
            words: house.words,
        }
    }

    _transformBook = (book) => {
        return {
            name: book.name,
            authors: book.authors,
            numberOfPages: book.numberOfPages,
            publisher: book.publisher,
            country: book.country,
            mediaType: book.mediaType,
            released: book.released,

        }

    }

}

